package com.yibo.user.service.user;

import com.yibo.feign.message.CheckWordServer;
import com.yibo.support.encry.MD5Helper;
import com.yibo.support.exception.YBException;
import com.yibo.support.helper.Assert;
import com.yibo.support.helper.ObjectHelper;
import com.yibo.support.inter.Command;
import com.yibo.support.pojo.IResult;
import com.yibo.db.user.entity.User;
import com.yibo.db.user.entity.UserInfo;
import com.yibo.db.user.entity.UserLevel;
import com.yibo.db.user.mapper.user.UserMapper;
import com.yibo.db.user.mapper.userinfo.UserInfoMapper;
import com.yibo.db.user.mapper.userlev.UserLevelMapper;
import com.yibo.user.object.RegisterUser;

import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

import static com.yibo.support.constant.MsgConstant.*;
import static com.yibo.user.constant.Constant.EMAIL;
import static com.yibo.user.constant.Constant.PHONE;

/**
 * 注册用户命令
 *
 * @author zhanglei
 */
public class RegisterUserCommand implements Command<Integer> {

    /**
     * 密码必须包含字母和数字
     */
    private static final String PASS_MATCH =  "^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,})$";

    private static final Pattern PATTERN = Pattern.compile(PASS_MATCH);

    private RegisterUser registerUser;

    public RegisterUserCommand(RegisterUser registerUser){
        this.registerUser = registerUser;
    }


    @Override
    public Integer execute() {
        //校验参数
        checkArgs();

        //校验验证码
        checkCheckWord();

        //添加用户基本信息
        getBean(UserMapper.class).insert(user());

        //添加用户扩展信息
        getBean(UserInfoMapper.class).insert(userInfo());

        //添加用户状态等级信息
        getBean(UserLevelMapper.class).insert(userLevel());
        return 1;
    }


    private void checkCheckWord(){
        String email = this.registerUser.getEmail();
        String phone = this.registerUser.getPhone();
        if(!ObjectHelper.isEmpty(email)){
            CheckWordServer server = getBean(CheckWordServer.class);
            IResult<String> result = server.emailCheckWord(email, "register", restModel -> {
                throw new YBException(SYSTEM_SERVER_EXCEPTION);
            });

            String checkWord = result.getData();
            Assert.isTrue(EMAIL_CHECK_WORD_ERROR,!this.registerUser.getCheckEmailWord().equals(checkWord));
            //删除验证码
            try {
                server.deleteCheckWord(email, "register");
            }catch (Exception e){
                //此处无需抛出异常
            }
        }

        if (!ObjectHelper.isEmpty(phone)) {
            //暂且不写，后面实现
        }



    }


    private UserLevel  userLevel(){
        return new UserLevel()
                .setUserId(this.registerUser.getUserId())
                //vip  无 0
                .setVip(0)
                //状态  正常状态 1
                .setStatus(1)
                //积分 0
                .setIntegral(0);
    }


    private UserInfo userInfo(){
        return new UserInfo()
                .setUserId(this.registerUser.getUserId())
                .setEmail(this.registerUser.getEmail())
                .setPhone(this.registerUser.getPhone());
    }


    private User   user(){
        return new User()
                .setUserId(this.registerUser.getUserId())
                .setPassword(MD5Helper.getMD5String(this.registerUser.getPassword()))
                .setUserName(this.registerUser.getUserName());
    }



    /**
     * 邮箱
     *
     * 用户ID
     *
     * 昵称
     *
     * 密码
     */
    private void checkArgs(){
        Assert.notEmpty(DATA_IS_EMPTY,this.registerUser);
        String userId = this.registerUser.getUserId();
        String password = this.registerUser.getPassword();
        String email = this.registerUser.getEmail();
        String phone = this.registerUser.getPhone();
        String userName = this.registerUser.getUserName();
        String emailCheckWord = this.registerUser.getCheckEmailWord();
        String phoneCheckWord = this.registerUser.getCheckPhoneWord();


        Assert.notEmpty(USER_ID_IS_EMPTY,userId);
        Assert.notEmpty(USER_NAME_IS_EMPTY,userName);
        Assert.notEmpty(PASSWORD_IS_EMPTY,password);
        Assert.allEmpty(EMAIL_IS_EMPTY,phone,email);
        Assert.isTrue(EMAIL_CHECK_WORD_IS_NULL,!ObjectHelper.isEmpty(phone) && ObjectHelper.isEmpty(phoneCheckWord));
        Assert.isTrue(EMAIL_CHECK_WORD_IS_NULL,!ObjectHelper.isEmpty(email) && ObjectHelper.isEmpty(emailCheckWord));

        //设置默认值
        this.registerUser.setEmail(email == null ? "***" : email);
        this.registerUser.setPhone(phone == null ? "***" : phone);
        //校验密码
        Assert.isTrue(PASSWORD_IS_WRONGFUL,!PATTERN.matcher(password).matches());

        //校验email和phone是 用户名否已经被注册
        User user = getBean(UserMapper.class).selectById(userId);
        Assert.isTrue(USER_ID_IS_EXIST,!ObjectHelper.isEmpty(user));

        UserInfoMapper mapper = getBean(UserInfoMapper.class);
        if(!ObjectHelper.isEmpty(email)){
            List<UserInfo> infoList = mapper.selectByMap(Collections.singletonMap(EMAIL,email));
            Assert.isTrue(EMAIL_EXIST,!ObjectHelper.isEmpty(infoList));
        }

        if(!ObjectHelper.isEmpty(phone)){
            List<UserInfo> infoList = mapper.selectByMap(Collections.singletonMap(PHONE,phone));
            Assert.isTrue(EMAIL_EXIST,!ObjectHelper.isEmpty(infoList));
        }

    }

}
